package com.idemon.springbootredismq;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

import java.util.concurrent.CountDownLatch;

@SpringBootApplication
public class SpringBootRedisMqApplication implements CommandLineRunner {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    public static void main(String[] args) {
        SpringApplication.run(SpringBootRedisMqApplication.class, args);
    }

    /**
     * 注入消息监听器
     * 将Receiver注入MessageListenerAdapter，并且指定接收消息的方法名receiveMsg
     *
     * @param receiver
     * @return
     */
    @Bean
    public MessageListenerAdapter listenerAdapter(Receiver receiver) {
        return new MessageListenerAdapter(receiver, "receiveMsg");
    }

    /**
     * 注入PatternTopic，并指定接收消息的Channel，发送的时候要指定同样的Channel
     *
     * @return
     */
    @Bean
    public PatternTopic patternTopic() {
        return new PatternTopic("chat");
    }

    /**
     * 注入消息监听容器
     * @param connectionFactory
     * @param listenerAdapter
     * @param patternTopic
     * @return
     */
    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                                   MessageListenerAdapter listenerAdapter, PatternTopic patternTopic) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(listenerAdapter, patternTopic);
        return container;
    }

    @Bean
    public CountDownLatch countDownLatch() {
        return new CountDownLatch(1);
    }

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private CountDownLatch countDownLatch;

    @Override
    public void run(String... args) throws Exception {
        logger.info("Send Msg ……");
        //指定发送消息的Channel，保持与接受Channel一致
        stringRedisTemplate.convertAndSend("chat", "Hello damon!");
        countDownLatch.await();
        System.exit(0);
    }
}
